package cn.oveay.classdesign.dao.impl;

import cn.oveay.classdesign.dao.UserDao;
import cn.oveay.classdesign.bean.basebean.User;
import cn.oveay.classdesign.util.jdbc.TxQueryRunner;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class UserDaoImpl implements UserDao {
    private QueryRunner qr = new TxQueryRunner();

    public List<User> findAll(){
        String sql = "select * from t_user";
        try {
            return qr.query(sql, new BeanListHandler<>(User.class));
        } catch (SQLException e) {
            throw new RuntimeException("UserDao Error.");
        }
    }

    public void inseartUser(User user) {
        String sql = "insert into t_user values(?,?,?,?,?)";
        Object[] params = {user.getId(), user.getName(), user.getPwd(), user.getNickname(), user.getOnline()};
        try {
            qr.update(sql, params);
        } catch (SQLException e) {
            throw new RuntimeException("UserDao Error. " + e.getMessage());
        }
    }


    public User findByName(String name) {
        String sql = "select * from t_user where name=?";
        try {
            return qr.query(sql, new BeanHandler<User>(User.class), name);
        } catch (SQLException e) {
            throw new RuntimeException("UserDao Error.");
        }
    }

    public void delete(String name) {
        String sql = "delete from t_user where name=?";
        try {
            qr.update(sql, name);
        } catch (SQLException e) {
            throw new RuntimeException("UserDao Error.");
        }
    }

    @Override
    public void updateUser(User user) {
        String sql = "update t_user set name=?,pwd=?,nickname=?,online=? where id=?";
        try {
            qr.update(sql, user.getName(), user.getPwd(), user.getNickname(), user.getOnline(), user.getId());
        } catch (SQLException e) {
            throw new RuntimeException("UserDao Error. " + e.getMessage());
        }
    }

    @Override
    public void trunOffOnlineToAllUser() {
        String sql = "update t_user set online=1";
        try {
            qr.update(sql);
        } catch (SQLException e) {
            throw new RuntimeException("UserDao Error. " + e.getMessage());
        }
    }

    @Override
    public User findById(String id) {
        String sql = "select * from t_user where id=?";
        try {
            return qr.query(sql, new BeanHandler<User>(User.class), id);
        } catch (SQLException e) {
            throw new RuntimeException("UserDao Error.");
        }
    }
}
